<template>
  <div class="app-container">
    <div id="app" style="width: 100%;display:inline-block">
      <el-form ref="searchForm" :model="searchForm" label-width="100px">
        <el-col :span="3">
          <el-form-item label="项目名称" label-width="70px">
            <el-input v-model="searchForm.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="合同状态" prop="progress_status" label-width="70px">
            <el-select v-model="searchForm.progress_status">
              <el-option v-for="(val, key) in contractStatus" :key="key" :label="val.name" :value="val.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="收款状态" prop="progress_status" label-width="70px">
            <el-select v-model="searchForm.receive_status">
              <el-option v-for="(val, key) in receive_status" :key="key" :label="val.name" :value="val.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="承建公司" prop="branch_id" label-width="70px">
            <el-select v-model="searchForm.branch_id">
              <el-option v-for="(val, key) in branch" :key="key" :label="val.name" :value="val.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="客户名称" prop="customer_id" label-width="70px">
            <!--<el-input v-model="ruleForm.customer_id"></el-input>-->
            <el-select
              v-model="searchForm.customer_id"
              filterable
              remote
              reserve-keyword
              placeholder="关键词搜索，空格表示全部"
              :remote-method="remoteMethod"
              :loading="loading.customers">
              <el-option
                v-for="item in customers"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="选择时间" prop="flow_status" label-width="70px">
            <el-date-picker
              v-model="searchForm.time"
              type="daterange"
              value-format = "timestamp"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions2">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <!--<el-form-item label="搜索" label-width="40px">-->
          <el-button @click="onSubmitSearchForm()" icon="el-icon-search" circle style="float: right;margin-right: 50%"></el-button>
          <!--</el-form-item>-->
        </el-col>
      </el-form>
    </div>
    <!--分页器-->
    <div style="padding:0 10px">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        :current-page="searchForm.currentPage"
        :page-sizes="[10,30,50,100]"
        :page-size="searchForm.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="searchForm.totalCount">
      </el-pagination>
    </div>
    <!--列表-->
    <table class="_table" border="0" cellpadding="0" cellspacing="0" style="width: 100%">
      <thead>
      <tr>
        <th>序号</th>
        <th width="200px">合同编号</th>
        <th width="200px">项目名称</th>
        <th>承建分公司</th>
        <th>委托单位</th>
        <th>合同状态</th>
        <th>收款状态</th>
        <th>合同金额</th>
        <th>已收金额</th>
        <th>付款方式</th>
        <th>备注</th>
        <th style="min-width: 350px">收款操作</th>
      </tr>
      </thead>
      <tbody v-for="(item,key) in list" :key="item.id">
      <tr>
        <td>{{item.id}}</td>
        <td>{{item.project_no}}</td>
        <td>{{item.name}}</td>
        <td>{{item.branch_id | parseBranch}}</td>
        <td>{{item.customer_name}}</td>
        <td>{{item.progress_status | parseProjectType}}</td>
        <td>{{item.receive_status | receiveStatus}}</td>
        <td>{{item.money_total}}</td>
        <td>{{item.money_received}}</td>
        <td>{{item.pay_way}}</td>
        <td>{{item.comment === null?'无':item.comment}}</td>
        <td>
          <el-button @click="onClickCreateBtn(item)"><i class="el-icon-edit"></i>增加收款记录</el-button>
          <el-button @click="onClickShowBtn(item)">显示/隐藏收款记录</el-button>
        </td>
      </tr>
      <!-- 当前项目的收款记录 （分页）-->
      <tr>
        <td colspan="10" style="background: #f0f0f0;color:green" v-show="item.showReceival">
          <ul>
            <li v-for="_item in item.children" :key = "_item.id">
              收款日期：{{_item.receive_date  | parseTime }} | 发票编号：{{_item.invoice_no}} | 金额：{{_item.money}} | 备注：{{_item.comment}}
            </li>
            <li v-show="item.children!==undefined && item.children.length<=0">
              没有收款记录
            </li>
          </ul>
        </td>
      </tr>
      </tbody>
    </table>
    <!--收款表单-->
    <el-dialog  title="新增收款" :visible.sync="visible.ruleForm" @close="closeDialog">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px">
        <el-form-item label="收款日期" prop="receive_date">
          <el-date-picker
            v-model="ruleForm.receive_date"
            type="date"
            value-format = "timestamp"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="收款状态">
          <el-select v-model="ruleForm.receive_status" placeholder="选择收款状态" style="width: 100%;">
            <el-option :label="val.name" :value="val.id" v-for="(val, key) in receiveStatus" :key="key"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="收款金额" prop="money">
          <el-input v-model.number="ruleForm.money"></el-input>
        </el-form-item>
        <el-form-item label="发票号" prop="invoice_no">
          <el-input v-model="ruleForm.invoice_no"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="comment">
          <el-input v-model="ruleForm.comment"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
          <el-button @click="visible.ruleForm = false">关闭</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  import { getProjects, parseContractType, parseOriginType, updateProject, getProject } from '../../api/project'
  import { createReceival, getReceivals } from '../../api/receival'
  import { replyRes } from '../../utils/res'
  import { parseTime } from '../../utils'
  import Store from '../../store'
  import _ from 'lodash'
  import { getCustomers } from '../../api/customer'
  import { getBranches } from '../../api/branch'

  /* -----------创建收款相关变量----------- */
  const defaultRuleForm = {
    project_id: null,
    money: null,
    invoice_no: '',
    comment: '',
    receive_date: null,
    receive_status: 0 // 收款状态
  }
  export default {
    data() {
      return {
        /* -----------列表相关状态--------------- */
        list: [],
        pageInfo: {
          page: 1,
          pageSize: 10,
          totalCount: 0
        },
        loading: {
          customers: false,
          users: false
        },
        branch: [
          { id: null, name: '全部' }
        ], // 承建单位
        customers: [],
        searchForm: {
          sign_status: null, // 合同签订
          progress_status: null, // 合同进度
          name: null,
          start_at: null,
          end_at: null,
          page: 1,
          pageSize: 10,
          totalCount: 0,
          time: []
        },
        /* -----------新增收款相关状态----------- */
        activeItem: {},
        activeReceivalId: 0,
        visible: {
          ruleForm: false
        },
        contractStatus: [
          { id: null, name: '全部' },
          { id: 0, name: '商务对接' },
          { id: 1, name: '生产中' },
          { id: 2, name: '完成生产' },
          { id: 3, name: '已完成' }
        ],
        receive_status: [
          { id: null, name: '全部' },
          { id: 0, name: '未收款' },
          { id: 1, name: '可收款' },
          { id: 2, name: '收款中' },
          { id: 3, name: '部分收款' },
          { id: 4, name: '完成收款' }
        ],
        receiveStatus: [
          { id: 0, name: '未收款' },
          { id: 1, name: '可收款' },
          { id: 2, name: '收款中' },
          { id: 3, name: '部分收款' },
          { id: 4, name: '完成收款' }
        ],
        rules: {
          receive_date: [
            { required: true, message: '请输入', trigger: 'blur' }
          ],
          money: [
            { type: 'number', required: true, message: '请输入正确的金额', trigger: 'blur' }
          ],
          // invoice_no: [
          //   { required: true, message: '请输入', trigger: 'blur' }
          // ],
          project_id: [
            { required: true, message: '请输入', trigger: 'blur' }
          ]
        },
        ruleForm: Object.assign({}, defaultRuleForm),
        pickerOptions2: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }]
        }
      }
    },
    filters: {
      parseTime: function(value) {
        if (!value) return ''
        value = value.toString()
        return parseTime(value, '{y}年{m}月{d}日')
      },
      parseContractType,
      parseOriginType,
      parseBranch: function(value) {
        const list = Store.state.user.branches
        for (const index in list) {
          if (parseInt(list[index].id) === value) {
            return list[index].name
          }
        }
        return value
      },
      // 将id转换为合同编号
      padStr: function(value) {
        return 'hj-' + _.padStart(value, 8, '0')
      },
      parseProjectType: function(value) {
        if (value === 0) {
          return '商务对接'
        }
        if (value === 1) {
          return '生产中'
        }
        if (value === 2) {
          return '完成生产'
        }
        if (value === 3) {
          return '已完成'
        }
        return value
      },
      receiveStatus: function(value) {
        if (value === 0) {
          return '未收款'
        }
        if (value === 1) {
          return '可收款'
        }
        if (value === 2) {
          return '收款中'
        }
        if (value === 3) {
          return '部分收款'
        }
        if (value === 4) {
          return '完成收款'
        }
        return value
      }
    },
    mounted() {
      this.fetchBranches()
      this.fetchList()
    },
    methods: {
      /* -----------列表相关方法--------------- */
      fetchList() {
        getProjects(this.searchForm).then(res => {
          this.list = res.data._items
          this.searchForm.totalCount = res.data._meta.totalCount
          console.log(this.list)
        })
      },
      // 获取收款状态的信息
      fetchProject(id) {
        getProject({ id: id }).then(res => {
          this.ruleForm.receive_status = res.data.receive_status
          console.log(this.ruleForm.receive_status)
        })
      },
      // 获取承建公司列表
      fetchBranches() {
        getBranches().then(res => {
          for (const x in res.data) {
            this.branch.push(res.data[x])
          }
        })
      },
      // 一页多少行
      handleSizeChange(pageSize) {
        this.searchForm.pageSize = pageSize
        this.fetchList()
      },
      // 翻页
      handlePageChange(currentPage) {
        this.searchForm.page = currentPage
        this.fetchList()
      },
      /* -----------创建收款相关方法----------- */
      onClickCreateBtn(item) {
        this.activeItem = item
        this.ruleForm.project_id = item.id
        this.fetchProject(item.id)
        if (item.children === undefined) {
          this.fetchReceivalList(item)
        }
        this.$set(item, 'showReceival', true)
        this.visible.ruleForm = true
      },
      // 显示当前项目的收款记录
      onClickShowBtn(item) {
        if (item.children === undefined) {
          this.fetchReceivalList(item)
        } else {
          item.showReceival = !item.showReceival
        }
      },
      submitForm(formName) {
        const id = this.ruleForm.project_id
        const status = this.ruleForm.receive_status
        this.$refs[formName].validate((valid) => {
          if (valid) {
            // 字段符合规则，创建收款记录
            if (this.activeReceivalId === 0) {
              // 调用新增接口并响应
              return createReceival(this.ruleForm).then(res => {
                if (replyRes(res)) {
                  this.visible.ruleForm = false
                  this.fetchReceivalList(this.activeItem)
                  this.activeItem.money_received = this.activeItem.money_received * 1 + this.ruleForm.money * 1
                }
              }).then(res => {
                console.log(this.ruleForm.project_id) // 这里为何不能拿到project_id
                updateProject({ receive_status: status, id: id }).then(res => {
                  console.log(res)
                  this.fetchList()
                })
              })
            }
          } else {
            console.log('ruleForm validate fail')
            return false
          }
        })
      },
      closeDialog() {
        this.ruleForm = Object.assign({}, defaultRuleForm)
      },
      /* -----------获取活动项目的收款记录相关方法----------- */
      // 获取当前活动对象的收款列表，并附加到该对象的children元素中
      fetchReceivalList(item) {
        getReceivals({ project_id: item.id }).then(res => {
          // 只有用$set方法为属性对象添加新的属性才能使状态异变自动反射到视图
          this.$set(item, 'children', res.data._items)
          this.$set(item, 'showReceival', true)
        })
      },
      /** 远程搜索客户列表方法 */
      remoteMethod(query) {
        this.loading.customers = true
        let params = {}
        if (query.trim() !== '') {
          params = { name: query.trim() }
        }
        getCustomers(params).then(res => {
          this.customers = res.data._items
          this.loading.customers = false
        })
      },
      onSubmitSearchForm() {
        if (this.searchForm.time !== null && this.searchForm.time.length > 0) {
          this.searchForm.start_at = this.searchForm.time[0]
          this.searchForm.end_at = this.searchForm.time[1]
        } else {
          this.searchForm.start_at = null
          this.searchForm.end_at = null
        }
        this.fetchList()
      },
      // 修改收款状态
      onReceiveStatus(item) {
        if (item.receive_status === 1) {
          return updateProject({ id: item.id, receive_status: 2 }).then(res => {
            this.fetchList()
          })
        }
      }
    }
  }
</script>
